var CardCode = function () {
  var template = /* html */ `
    <div class="card-code">
      <div ref="cardCode" class="card-code-qrcode" v-if="isShow">
        <div class="card-code-div" ref="qrCode"></div>
        <div style="text-align:center;font-size:20px;margin-top:6px">
          <span ref="qrCodeText">{{internetThingsCard}}</span>
        </div>
      </div>
      <div class="card-code-qrcode">
        <img :src="imgUrl">
      </div>
    </div>
  `;

  return {
    props: {
      card: {
        type: Object,
        required: true
      }
    },

    data: function () {
      return {
        isShow: true,
        internetThingsCard: this.card.internetThingsCard,
        qrcode: null,
        imgUrl: ''
      };
    },

    mounted: function () {
      this.createQrcode();
      setTimeout(() => {
        this.drawQrcode();
      }, 500);
    },

    methods: {
      createQrcode: function () {
        var card = this.card;
        var internetThingsCard = card.internetThingsCard;
        var origin = 'https://www.shinehao.net/weixin';

        var qrCodeEl = this.$refs['qrCode'];
        this.qrcode = new QRCode(qrCodeEl, {
          text: `${origin}/weiXin/s?i=${internetThingsCard}`,
          width: 150,
          height: 150,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.L
        });
      },

      drawQrcode: function () {
        var canvas = document.createElement('canvas');
        var imgDom = $(this.$el).find('.card-code-div img')[0];
        var $cardCode = $(this.$refs['cardCode']);
        var canvasWidth = $cardCode.width();
        var canvasHeight = $cardCode.height();
        canvas.width = canvasWidth;
        canvas.height = canvasHeight;

        var ctx = canvas.getContext('2d');
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvasWidth, canvasHeight);
        ctx.drawImage(imgDom, (canvasWidth - imgDom.width) / 2, 0);

        var textDom = this.$refs['qrCodeText'];
        var textWidth = $(textDom).width();
        ctx.fillStyle = "#000000";
        ctx.font="20px Arial";
        ctx.fillText(this.internetThingsCard, (canvasWidth - textWidth) / 2, 174);

        this.imgUrl = canvas.toDataURL('image/jpeg', 1.0);
        this.isShow = false;
      }
    },

    template: template
  };
}();
